package com.icinfo.cloud.provider.common.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * 获得http请求头工具
 *
 * @author
 */
public class AuthHeaderUtil {
    public static final Log log = LogFactory.getLog(HeaderUtil.class);

    /**
     * 鉴权token的header名
     */
    private static final String AUTHORIZATION = "Authorization";


    public static Map<String, String> headerInfo() {
        return getHeaders(getHttpServletRequest());
    }

    /**
     * 仅获取鉴权token的header
     *
     * @return
     */
    public static Map<String, String> authHeader() {
        HttpServletRequest request = getHttpServletRequest();
        //仅处理鉴权header
        Map<String, String> headers = getHeaders(request);
        //仅将鉴权header放入
        Map<String, String> authHeader = new HashMap<>();
        headers.forEach((k, v) -> {
            if (!AUTHORIZATION.equalsIgnoreCase(k)) {
                return;
            }
            authHeader.put(AUTHORIZATION, v);
        });
        return authHeader;
    }

    private static HttpServletRequest getHttpServletRequest() {

        try {
            // 这种方式获取的HttpServletRequest是线程安全的
            return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        } catch (Exception e) {

            return null;
        }
    }

    private static Map<String, String> getHeaders(HttpServletRequest request) {

        Map<String, String> map = new LinkedHashMap<>();
        if (request != null && request.getHeaderNames() != null) {
            Enumeration<String> enums = request.getHeaderNames();
            while (enums.hasMoreElements()) {
                String key = enums.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
        }

        return map;
    }

}
